import {useState,useEffect} from 'react'
import axios from 'axios'
import {get} from './api/instance.js'
import './App.css'
import { ProductCard,Button, SubmitBar, Checkbox} from 'react-vant';
// import './demo/style.less';
function App() {
  let [list,setList]=useState([])
  useEffect(()=>{
    // axios.get('http://localhost:3000/shop')
    get('shop')
  .then(res=>{
    setList(res.data)
  })
  },[])
  const check=(id,checked)=>{
  let arr=[...list]
  let index=list.findIndex(item=>item.id==id)
  arr[index].flag=checked
  setList(arr)
}
const all=(checked)=>{
  let arr=[...list]
  arr.forEach(item=>item.flag=checked)
  setList(arr)
}
const sum=        
list.reduce((sum,item)=>{
  if(item.flag) {sum+= Number(item.num)*Number(item.price)}
  return sum
},0)
  return (
    <>
    {
      list.map(item=>{
        return       <ProductCard
        key={item.id}
        num={item.num}
        price={item.price}
        desc={item.fail}
        title={item.type}
        thumb="https://img.yzcdn.cn/vant/ipad.jpeg"
        footer={
          <>
          <input type="checkbox" className='box'
          checked={item.flag}
          onChange={(e)=>check(item.id,e.target.checked)}
          />


          <Button size='mini' plain style={{ marginRight: 41}} onClick={()=>{
                          let arr=[...list]
                          let index=list.findIndex(v=>v.id==item.id)
                          arr.splice(index,1)
                          setList(arr)
          }}>删除</Button>
            <Button size="" round plain style={{ marginRight: 4 }} onClick={()=>{
              let arr=[...list]
              let index=list.findIndex(v=>v.id==item.id)
              if(arr[index].num>=1){
                arr[index].num--
              }
              setList(arr)
            }}>
              -
            </Button>
            <Button onClick={()=>{
              let arr=[...list]
              let index=list.findIndex(v=>v.id==item.id)
              arr[index].num++
              setList(arr)
            }}>
              +
            </Button>
            
          </>
        }
      />
      })
    }
    <div className="demo-submit-bar">
    <SubmitBar
      price={
        list.reduce((sum,item)=>{
          if(item.flag) {sum+= Number(item.num)*Number(item.price)}
          return sum
        },0)*100
      }
      buttonText="提交订单"
    >
      <Checkbox 
      checked={
        list.every(item=>item.flag)
      }
      onChange={(e)=>all(e)}>全选</Checkbox>
    </SubmitBar>
    </div>

    </>
  )
}

export default App;
